package tacos.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private UserDetailsService userDetailsService;

    @Autowired
    public void setUserDetailsService(@Qualifier("userDetailsServiceImpl") UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    // 声明一个密码转码器
    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                // encoder()方法上有 @Bean 注解，对于 encoder()的任何调用都会被拦截，并且返回应用上下文中的 Bean 实例。
                .passwordEncoder(encoder());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/static/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                    .antMatchers("/design", "/orders", "/testhome")
                        .hasRole("USER")
                    .antMatchers("/", "/**").access("permitAll")

                // 告诉 Spring Security 自定义登录页的路径是什么
                .and()
                .formLogin()
                    .loginPage("/login")
                // 自定义 “路径” 和 “输入域的名称”
//                .defaultSuccessUrl("/design", true)

                // 启用退出功能
                .and()
                .logout()
                    .logoutSuccessUrl("/");

                // 解决启用 Spring Security 以后发现 H2 Database 的控制台登陆页面是无法访问的（403）
                http.csrf().ignoringAntMatchers("/h2-console/**");


                // 解决启用 Spring Security 以后发现 H2 Database能进去控制台的登陆页面（输入数据库用户名和密码的页面），但是登陆以后出现界面是无法显示（空白页面）。
                http.headers().frameOptions().sameOrigin();

    }
}
